﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Bzzb.Model;
using FreeSql.Internal.Model;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Bzzb.Controllers
{
    public class BaoZhangGongJuController : BaseController
    {
        private readonly ILogger<BaoZhangGongJuController> _logger;
        public BaoZhangGongJuController(ILogger<BaoZhangGongJuController> logger, IFreeSql fsql) : base(fsql)
        {
            this._logger = logger;
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Index([FromForm] string content, [FromForm] int doPage = 1, [FromForm] int pageNumber = 1, [FromForm] int pageSize = 10)
        {
            DynamicFilterInfo dyfilter = JsonConvert.DeserializeObject<DynamicFilterInfo>(@"
{
  'Logic' : 'Or',
  'Filters' :
  [
    {
      'Field' : 'Name',
      'Operator' : 'Contains',
      'Value' : '" + content + @"',
    },{
      'Field' : 'Gjxbh',
      'Operator' : 'Contains',
      'Value' : '" + content + @"',
    }
  ]
}
");
            long total = 0;
            List<BaoZhangGongJu> baozhanggongjus;
            if (doPage == 0)
            {
                baozhanggongjus = await _fsql.Select<BaoZhangGongJu>().WhereDynamicFilter(dyfilter).ToListAsync();
            }
            else {
                baozhanggongjus = await _fsql.Select<BaoZhangGongJu>().WhereDynamicFilter(dyfilter).Count(out total).Page(pageNumber, pageSize).ToListAsync();
                
            }
            JArray ja_baozhanggongju = new();
            foreach (var baozhanggongju in baozhanggongjus)
            {
                JObject jo_baozhanggongju = JObject.FromObject(baozhanggongju);
                BaoZhangZhuangBeiIOT baozhangzhuangbeiiot = await _fsql.Select<BaoZhangZhuangBeiIOT>().Where(bzzbiot => bzzbiot.Bzzbtid == 5 && bzzbiot.Bzzbid == 0 && bzzbiot.Jtid == baozhanggongju.Id && bzzbiot.Gjid == 0).OrderByDescending(bzzbiot => bzzbiot.Id).Limit(1).ToOneAsync();
                jo_baozhanggongju.Add("position", baozhangzhuangbeiiot == null ? null : JObject.FromObject(baozhangzhuangbeiiot));
                ja_baozhanggongju.Add(jo_baozhanggongju);
            }
            JObject data = new();
            data.Add("total", total);
            data.Add("list", ja_baozhanggongju);
            return RenderJson(data: data);
        }

        [HttpPost]
        public IDictionary<string, object> Save([FromForm] BaoZhangGongJu baozhanggongju)
        {
            _fsql.Transaction(() =>
            {
                // 先增加工具库
                long id = _fsql.Insert(baozhanggongju).ExecuteIdentity();
                baozhanggongju.Id = id;
                // 更新工具库编码
                _fsql.Update<BaoZhangGongJu>(id).Set(bzgj => bzgj.Gjxbh, baozhanggongju.Gjxbh + "-" + String.Format("{0:D4}", id)).ExecuteAffrows();
                // 批量增加对应工具
                if (baozhanggongju.Gjxq.Length > 0)
                {
                    var items = new List<BaoZhangGongJuTools>();
                    foreach (long tid in baozhanggongju.Gjxq)
                    {
                        items.Add(new BaoZhangGongJuTools { Bzgjid = id, Tid = tid });
                    }
                    _fsql.Insert(items).ExecuteAffrows();
                }
            });

            return RenderJson(data: baozhanggongju);
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Delete([FromForm] long id) {
            int affrows = 0;
            _fsql.Transaction(() => {
                affrows = _fsql.Delete<BaoZhangGongJu>().Where(bzgj => bzgj.Id == id).ExecuteAffrows();
                // 删除工具箱对应的工具
                _fsql.Delete<BaoZhangGongJuTools>().Where(bzgjt => bzgjt.Bzgjid == id).ExecuteAffrows();
            });
            
            return RenderJson(data: affrows);
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Update([FromForm] BaoZhangGongJu baozhanggongju) {
            int affrows = 0;
            _fsql.Transaction(() => {
                // 更新保障工具
                affrows = _fsql.Update<BaoZhangGongJu>().SetSourceIgnore(baozhanggongju, colval => colval == null).ExecuteAffrows();
                // 删除以前所选工具
                _fsql.Delete<BaoZhangGongJuTools>().Where(bzgjt => bzgjt.Bzgjid == baozhanggongju.Id).ExecuteAffrows();
                // 批量新增加对应工具
                if (baozhanggongju.Gjxq.Length > 0)
                {
                    var items = new List<BaoZhangGongJuTools>();
                    foreach (long tid in baozhanggongju.Gjxq)
                    {
                        items.Add(new BaoZhangGongJuTools { Bzgjid = baozhanggongju.Id, Tid = tid });
                    }
                    _fsql.Insert(items).ExecuteAffrows();
                }
            });
            return RenderJson(data: affrows);
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Show([FromForm] long id) {
            BaoZhangGongJu baozhanggongju = await _fsql.Select<BaoZhangGongJu>().Where(bzgj => bzgj.Id == id).ToOneAsync();
            return RenderJson(data: baozhanggongju);
        }
    }
}
